# -*- coding: utf-8 -*-
# @Time    : 2024/10/13 16:05
# @Author  : 荒
# @FileName: 支付宝签名.py
# @Software: PyCharm

import datetime
import json

# 构造字典
params = {
    'app_id': "9021000141626223",
    'method': 'alipay.trade.page.pay',
    'format': 'JSON',
    'return_url': "http://127.0.0.1:8001/pay/notify/",
    'notify_url': "http://127.0.0.1:8001/pay/notify/",
    'charset': 'utf-8',
    'sign_type': 'RSA2',
    'timestamp': datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
    'version': '1.0',
    'biz_content': json.dumps({
        'out_trade_no': 'lkkkkkk',
        'product_code': 'FAST_INSTANT_TRADE_PAY',
        'total_amount': 1.11,
        'subject': "x1"
    }, separators=(',', ':'))
}

# 获取待签名的字符串
unsigned_string = "&".join(["{0}={1}".format(k, params[k]) for k in sorted(params)])
print(unsigned_string)

# 签名 SHA256WithRSA(对应sign_type为RSA2)
from Crypto.PublicKey import RSA
from Crypto.Signature import PKCS1_v1_5
from Crypto.Hash import SHA256
from base64 import decodebytes, encodebytes

# SHA256WithRSA + 应用私钥 对待签名的字符串 进行签名
private_key = RSA.importKey(open("../files/应用私钥RSA2048.txt").read())
signer = PKCS1_v1_5.new(private_key)
signature = signer.sign(SHA256.new(unsigned_string.encode('utf-8')))

# 对签名之后的执行进行base64 编码，转换为字符串
sign_string = encodebytes(signature).decode("utf8").replace('\n', '')

# 把生成的签名赋值给sign参数，拼接到请求参数中。

from urllib.parse import quote_plus
result = "&".join(["{0}={1}".format(k, quote_plus(params[k])) for k in sorted(params)])
result = result + "&sign=" + quote_plus(sign_string)

gateway = "https://openapi.alipaydev.com/gateway.do"
pay_url = "{}?{}".format(gateway, result)

print(pay_url)